import requests
from selenium import webdriver
from lxml import etree
from urllib.parse import urlencode
import time
from hashlib import md5


class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                          headers=self.headers)
        return r.json()

    def PostPic_base64(self, base64_str, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
            'file_base64': base64_str
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()


chaojiying = Chaojiying_Client('Future119', 'p0lqv59l', '971377')

driver = webdriver.Chrome()
driver.maximize_window()
headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Pragma": "no-cache",
    "Referer": "https://www.bjcourt.gov.cn/cpws/index.htm?st=1&q=&sxnflx=0&prompt=&dsrName=&ajmc=&ajlb=&jbfyId=&zscq=&ay=&ah=&cwslbmc=&startCprq=&endCprq=&startFbrq=&endFbrq=&page=10",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-User": "?1",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\""
}
cookies = {
    "thguid-r": "1776670491289841664",
    "__jsluid_s": "68bdfdab8d1fec4f293c3d89e59b025f",
    "vh2PJqrvyx": "MDAwM2IyYWYxZTQwMDAwMDAwMDQwP3siRSYxNzUxODgzNTE3",
    "6JDgKK8lEy": "MDAwM2IyYWYxZTQwMDAwMDAwMDMwLQhnHgIxNzUxODgzNTE3",
    "JSESSIONID": "node01cu4qt92qnpqz10b6te609tqnl101072059.node0"
}
url = "https://www.bjcourt.gov.cn/cpws/index.htm"
params = {
    "st": "1",
    "q": "",
    "sxnflx": "0",
    "prompt": "",
    "dsrName": "",
    "ajmc": "",
    "ajlb": "",
    "jbfyId": "",
    "zscq": "",
    "ay": "",
    "ah": "",
    "cwslbmc": "",
    "startCprq": "",
    "endCprq": "",
    "startFbrq": "",
    "endFbrq": "",
    "page": "1"
}
for page in range(1, 20 + 1):
    params["page"] = page
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    time.sleep(5)
    # 使用页面内容判断是否出现验证码页面
    html_str = response.content.decode()
    if "<title>北京法院审判信息网-裁判文书</title>" not in html_str:
        params["page"] = page
        driver.get(f"{url}?{urlencode(params)}")
        time.sleep(3)
        html_str = driver.page_source
        if "<title>北京法院审判信息网-裁判文书</title>" not in html_str:
            driver.find_element("xpath", "//img[@id='yzmImg']").screenshot("yzm.png")
            result = chaojiying.PostPic(open("yzm.png", "rb").read(), 1902)
            yzm_code = result["pic_str"]
            driver.find_element("xpath", "//input[@id='yzmInput']").send_keys(yzm_code)
            driver.find_element("xpath", "//a[@id='loginBtn']").click()
            time.sleep(3)
            html_str = driver.page_source

    li_list = etree.HTML(html_str).xpath("//li[@class='refushCpws']")
    for li in li_list:
        title = "".join(li.xpath("./a/text()")).strip()
        print(page, title)

driver.quit()
